package com.smfx.yxt.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionSynchronizationAdapter;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import com.smfx.yxt.common.Const;
import com.smfx.yxt.common.MenuConst;
import com.smfx.yxt.common.RspResult;
import com.smfx.yxt.common.enums.RelationType;
import com.smfx.yxt.common.enums.Status;
import com.smfx.yxt.daoSqlserver.AttachmentListMapper;
import com.smfx.yxt.daoSqlserver.CourseClassDateMapper;
import com.smfx.yxt.daoSqlserver.KccsCourseInfoMapper;
import com.smfx.yxt.daoSqlserver.KccsCourseStudentSignMapper;
import com.smfx.yxt.daoSqlserver.TeacherInfoMapper;
import com.smfx.yxt.exception.ExpirationException;
import com.smfx.yxt.model.AttachmentList;
import com.smfx.yxt.model.CourseClassDate;
import com.smfx.yxt.model.KccsCourseInfo;
import com.smfx.yxt.model.KccsCourseStudentSign;
import com.smfx.yxt.model.TeacherInfo;
import com.smfx.yxt.page.Page;
import com.smfx.yxt.reqVo.AttachRelationReqVO;
import com.smfx.yxt.reqVo.BaseQueryVO;
import com.smfx.yxt.reqVo.KccsCourseQueryVO;
import com.smfx.yxt.reqVo.KccsCourseReqVO;
import com.smfx.yxt.reqVo.KccsStudentSignReqVO;
import com.smfx.yxt.service.IKccsCourseInfoService;
import com.smfx.yxt.utils.BeanUtils;
import com.smfx.yxt.utils.PropertiesUtil;
import com.smfx.yxt.view.KccsCourseSignCountView;
import com.smfx.yxt.view.KccsCourseStudentSignTotal;
import com.smfx.yxt.view.KccsCourseStudentSignView;
import com.smfx.yxt.view.KccsCourseView;
import com.smfx.yxt.wechat.utils.TemplateUtil;

@Service("KccsCourseInfoService")
public class KccsCourseInfoServiceImpl implements IKccsCourseInfoService {

	@Autowired
	private KccsCourseInfoMapper kccsCourseInfoMapper;
	@Autowired
	private AttachmentListMapper attachmentListMapper;
	@Autowired
	private KccsCourseStudentSignMapper kccsCourseStudentSignMapper;
	@Autowired
	private TeacherInfoMapper teacherInfoMapper;
	@Autowired
	private CourseClassDateMapper courseClassDateMapper;
	
	@Override
	public int insertSelective(KccsCourseInfo record) {
		return kccsCourseInfoMapper.insertSelective(record);
	}

	@Override
	public KccsCourseInfo selectByPrimaryKey(Integer id) {
		return kccsCourseInfoMapper.selectByPrimaryKey(id);
	}

	@Override
	public int updateByPrimaryKeySelective(KccsCourseInfo record) {
		return kccsCourseInfoMapper.updateByPrimaryKeySelective(record);
	}
	
	@Override
	public KccsCourseView selectSignCourseDetail(BaseQueryVO vo) {
		KccsCourseView view = kccsCourseInfoMapper.selectSignCourseDetail(vo);
		setKccsCourseItem(view);
		if(StringUtils.isNotBlank(view.getMainImg())) {
			Map<String, Object> map = new HashMap<>();
			map.put("type", RelationType.KCCS_COURSE.getCode());
			map.put("objId", vo.getId());
			List<AttachmentList> attachmentList = attachmentListMapper.queryAttachmentListByRelationId(map);
			view.setAttachList(attachmentList);
		}
		return view;
	}

	@Override
	public void addAndUpdate(KccsCourseReqVO vo) {
		if(vo.getId() == null) {
			kccsCourseInfoMapper.insertSelective(vo);
			if(StringUtils.isNotBlank(vo.getAttachIds())) {
				AttachRelationReqVO attachReqVO = new AttachRelationReqVO();
				String[] array = vo.getAttachIds().split(",");
				attachReqVO.setRelationId(Long.valueOf(vo.getId()));
				attachReqVO.setAttachIds(array);
				attachmentListMapper.updateRelationIdByIds(attachReqVO);
			}
		}else {
			kccsCourseInfoMapper.updateByPrimaryKeySelective(vo);
			AttachRelationReqVO attachReqVO = new AttachRelationReqVO();
			attachReqVO.setRelationId(Long.valueOf(vo.getId()));
			if(StringUtils.isNotBlank(vo.getAttachIds())) {
				String[] array = vo.getAttachIds().split(",");
				attachReqVO.setAttachIds(array);
			}else {
				String[] array = {"0"};
				attachReqVO.setAttachIds(array);
			}
			attachmentListMapper.updateInvaildForRevByIds(attachReqVO);
			if(StringUtils.isNotBlank(vo.getAttachIds())) {
				attachmentListMapper.updateRelationIdByIds(attachReqVO);
			}
		}
	}

	@Override
	public List<KccsCourseStudentSignView> selectSignedListForClass(KccsCourseQueryVO vo) {
		return kccsCourseStudentSignMapper.selectSignedListForClass(vo);
	}

	@Override
	public List<KccsCourseStudentSignView> selectNoSignListForClass(KccsCourseQueryVO vo) {
		return kccsCourseStudentSignMapper.selectNoSignListForClass(vo);
	}

	@Override
	public KccsCourseStudentSignView selectSignedCourseForStudent(KccsCourseQueryVO vo) {
		return kccsCourseStudentSignMapper.selectSignedCourseForStudent(vo);
	}

	@Override
	public List<KccsCourseStudentSignView> selectSignListForParent(KccsCourseQueryVO vo) {
		return kccsCourseStudentSignMapper.selectSignListForParent(vo);
	}
	
	@Override
	public RspResult insertSign(KccsStudentSignReqVO reqVO) {
		for(KccsCourseStudentSign record : reqVO.getList()) {
			KccsCourseQueryVO vo = new KccsCourseQueryVO();
			vo.setTermId(reqVO.getTermId());
			vo.setCourseId(record.getCourseId());
			vo.setClassDate(record.getSignClassDate());
			if(isCourseSignLimit(vo)) {
				return new RspResult(Status.FAIL.getCode(), record.getSignClassDate() + "的" + 
						record.getCourseName() + "课程人数已满，请选择其它课程！");
			}
		}
		int result = kccsCourseStudentSignMapper.insertSign(reqVO);
		if(result > 0) {
			return new RspResult(Status.SUCCESS);
		}
		return new RspResult(Status.FAIL);
	}

	@Override
	public RspResult updateChangeSign(KccsStudentSignReqVO reqVO) {
		kccsCourseStudentSignMapper.updateInvalidStudentSign(reqVO);
		for(KccsCourseStudentSign record : reqVO.getList()) {
			KccsCourseQueryVO vo = new KccsCourseQueryVO();
			vo.setTermId(reqVO.getTermId());
			vo.setCourseId(record.getCourseId());
			vo.setClassDate(record.getSignClassDate());
			if(isCourseSignLimit(vo)) {
				throw new ExpirationException(record.getSignClassDate() + "的" + 
						record.getCourseName() + "课程人数已满，请选择其它课程！");
			}
		}
		int result = kccsCourseStudentSignMapper.insertSign(reqVO);
		if(result > 0) {
			return new RspResult(Status.SUCCESS);
		}
		return new RspResult(Status.FAIL);
	}

	@Override
	public RspResult updateApprovalCourse(KccsCourseReqVO vo) {
		KccsCourseInfo courseInfo = kccsCourseInfoMapper.selectByPrimaryKey(vo.getId());
		if(courseInfo.getIsAgree() != 0) {
			return new RspResult(Status.EXPIRED_DATA);
		}
		vo.setUpdateTime(new Date());
		addAndUpdate(vo);
		courseInfo.setIsAgree(vo.getIsAgree());
		ThreadExecute(courseInfo);
		return new RspResult(Status.SUCCESS);
	}

	@Override
	public boolean isFullForCourseId(BaseQueryVO vo) {
		KccsCourseInfo courseInfo = kccsCourseInfoMapper.selectByPrimaryKey(vo.getId());
		if(courseInfo.getLimitNum() != null) {
			int count = kccsCourseStudentSignMapper.seletCountByCourseId(vo);
			if(count >= courseInfo.getLimitNum().intValue()) {
				return true;
			}
		}
		return false;
	}

	@Override
	public List<KccsCourseStudentSignView> selectSignListForTeachingByCourseId(KccsCourseQueryVO vo) {
		return kccsCourseStudentSignMapper.selectSignListForTeachingByCourseId(vo);
	}

	@Override
	public List<KccsCourseView> selectSignCourseList(BaseQueryVO vo) {
		List<KccsCourseView> list = kccsCourseInfoMapper.selectSignCourseList(vo);
		for(KccsCourseView view : list) {
			if(StringUtils.isNotBlank(view.getClassDate())){
				setKccsCourseItem(view);
			}
		}
		return list;
	}

	@Override
	public boolean isCourseSignLimit(KccsCourseQueryVO vo) {
		int result = kccsCourseInfoMapper.selectCourseSignLimit(vo);
		return result > 0 ? false : true;
	}
	
	@Override
	public KccsCourseView selectViewById(Integer courseId) {
		KccsCourseInfo courseInfo = kccsCourseInfoMapper.selectByPrimaryKey(courseId);
		KccsCourseView view = BeanUtils.copyAs(courseInfo, KccsCourseView.class);
		if(StringUtils.isNotBlank(view.getMainImg())) {
			Map<String, Object> map = new HashMap<>();
			map.put("type", RelationType.KCCS_COURSE.getCode());
			map.put("objId", courseId);
			List<AttachmentList> attachmentList = attachmentListMapper.queryAttachmentListByRelationId(map);
			view.setAttachList(attachmentList);
		}
		return view;
	}

	@Override
	public List<KccsCourseInfo> selectPendingList(Page<KccsCourseInfo> page) {
		return kccsCourseInfoMapper.selectPendingList(page);
	}

	@Override
	public List<KccsCourseInfo> selectApprovedList(Page<KccsCourseInfo> page) {
		return kccsCourseInfoMapper.selectApprovedList(page);
	}

	@Override
	public List<KccsCourseInfo> selectApplyList(Integer teacherId) {
		return kccsCourseInfoMapper.selectApplyList(teacherId);
	}

	@Override
	public List<KccsCourseInfo> selectListForTeaching(Integer teacherId) {
		return kccsCourseInfoMapper.selectListForTeaching(teacherId);
	}

	private void setKccsCourseItem(KccsCourseView view) {
		List<KccsCourseSignCountView> signList = view.getSignCountList();
		String[] dateArray = view.getClassDate().split(",");
		if(signList.size() == 1 && StringUtils.isBlank(
				signList.get(0).getSignClassDate())) {
			view.setSignCountList(new ArrayList<>());
			for(String date : dateArray) {
				KccsCourseSignCountView signView = new KccsCourseSignCountView();
				signView.setCourseId(view.getId());
				signView.setCourseName(view.getCourseName());
				signView.setCourseType(view.getCourseType());
				signView.setCourseNo(view.getCourseNo());
				signView.setLimitNum(view.getLimitNum());
				signView.setSignClassDate(date);
				signView.setStudentSignCount(0);
				view.getSignCountList().add(signView);
			}
		}else {
			for(String date : dateArray) {
				boolean isExists = false;
				for(KccsCourseSignCountView signView : signList) {
					if(signView.getSignClassDate().equals(date)) {
						isExists = true;
						break;
					}
				}
				if(!isExists) {
					KccsCourseSignCountView signView = new KccsCourseSignCountView();
					signView.setCourseId(view.getId());
					signView.setCourseName(view.getCourseName());
					signView.setCourseType(view.getCourseType());
					signView.setCourseNo(view.getCourseNo());
					signView.setLimitNum(view.getLimitNum());
					signView.setSignClassDate(date);
					signView.setStudentSignCount(0);
					view.getSignCountList().add(signView);
				}
			}
		}
	}
	
	void ThreadExecute(KccsCourseInfo apply) {
		TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
	        @Override
	        public void afterCommit() {
	        	String reqUrl = Const.BASEPATH + Const.TEACHER_ROLE + 
	        			MenuConst.INTEREST_COURSE + "/detail/" + apply.getId();
	        	String templateId = PropertiesUtil.getProperty("work_approval_result_template");
	        	TeacherInfo teacher = teacherInfoMapper.selectByPrimaryKey(apply.getCreaterId());
	        	TemplateUtil.approvalResultSend(teacher.getOpenid2(), "您好！您创建的课程已被审批", "课程超市", 
						apply.getIsAgree() == 1 ? "同意开课" : "不同意开课", new Date(), templateId, reqUrl);
	        }
	    });
	}

	@Override
	public int updateCourseType(List<KccsCourseInfo> list) {
		return kccsCourseInfoMapper.updateCourseType(list);
	}

	@Override
	public List<KccsCourseStudentSignTotal> selectStudentSignListByPage(Page<KccsCourseStudentSignTotal> page) {
		return kccsCourseStudentSignMapper.selectStudentSignListByPage(page);
	}

	@Override
	public List<KccsCourseInfo> selectListByPage(Page<KccsCourseInfo> page) {
		return kccsCourseInfoMapper.selectListByPage(page);
	}

	@Override
	public int updateBatchCourseStatus(List<String> list, Integer isAgree, Integer updaterId, String updater) {
		return kccsCourseInfoMapper.updateBatchCourseStatus(list, isAgree, updaterId, updater);
	}

	@Override
	public CourseClassDate selectCourseClassDate() {
		return courseClassDateMapper.selectCourseClassDate();
	}

	@Override
	public int updateCourseClassDate(CourseClassDate record) {
		return courseClassDateMapper.updateByPrimaryKeySelective(record);
	}

	@Override
	public List<KccsCourseStudentSignTotal> selectCourseClazzTotal(KccsCourseQueryVO vo) {
		return kccsCourseStudentSignMapper.selectCourseClazzTotal(vo);
	}
	
}
